from rest_framework import status
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
# from new_mall.libs.yuntongxun.sms import CCP
from rest_framework.response import Response
import logging
from . import constants
from celery_tasks.sms.tasks import send_sms_code


logger = logging.getLogger('django')


# Create your views here.
class SMSCodeView(APIView):
    """短信验证码"""
    def get(self, request, mobile):
        #1.创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')

        #2.先从redis获取发送标记
        send_flag = redis_conn.get('send_flag_%s' %mobile)
        #3.如果取到了标记，说明此手机号频繁发送短信
        if send_flag:
            return Response({'message': '手机频繁发送短信'}, status=status.HTTP_400_BAD_REQUEST)
        #4.生成验证码
        sms_code = '%06d' % randint(0, 999999)
        logger.info(sms_code)
        #创建redis管道，把多次redis连接操作放入管道，将来一次性执行，减少连接操作
        pl = redis_conn.pipeline()
        #5.把验证码存储到redis数据库
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        #6.存储一个标记，表示手机号已发送过短信 标记有效期60s
        # redis_conn.setex('send_flag_%s' %mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.setex('send_flag_%s' %mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()
        #7.利用容联云通讯发送短信验证码
        #CCP().send_template_sms(self, to-手机号, datas[验证码，分钟], temp_id-1)
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES//60], 1)
        send_sms_code.delay(mobile, sms_code) #必须加个delay
        #8.响应
        return Response({'message': 'ok'})

        # #1.生成验证码不够在前面补充0
        # sms_code = '%06d' % randint(0, 999999)
        # logger.info(sms_code)
        # #2.创建redis链接对象
        # redis_conn = get_redis_connection('verify_codes')
        # #3.把验证码存储到redis数据库;过期时间5分钟，为每个手机号赋值sms_code
        # redis_conn.setex('sms_%s' % mobile, 300, sms_code)
        # #4.利用容联云通讯发送短信验证码
        # #CCP().send_template_sms(self, to-手机号, datas[验证码，分钟], temp_id-1)
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # #5.响应
        # return  Response({'message': 'ok'})